package com.live.shop.scene.server;

import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.live.shop.BaseActivity;
import com.live.shop.R;
import com.live.shop.home.setting.PermissionActivity;
import com.live.shop.model.ProductGroupModel;
import com.live.shop.scene.tool.ServerDataTool;
import com.live.shop.scene.ws.WsMessageEvent;
import com.live.shop.scene.ws.WsServer;
import com.live.shop.scene.ws.WsStatus;
import com.live.shop.service.WsWindowService;
import com.live.shop.sql.ProductGroupListDatabase;
import com.live.shop.tool.GetUtil;
import com.live.shop.tool.StatusBarUtils;
import com.live.shop.view.ToastBottomUtils;
import com.live.shop.view.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class WsHomeServerActivity extends BaseActivity {
    ImageButton ws_home_server_back;
    RelativeLayout ws_home_server_group_list;
    RelativeLayout ws_home_server_window;
    TextView ws_home_server_location_ip;
    TextView ws_home_server_location_port;
    TextView ws_home_server_serverstatus;
    TextView ws_home_server_clientstatus;

    LinearLayout ws_home_server_sync_linearlayout;
    TextView ws_home_server_sync_sendnum;
    TextView ws_home_server_sync_totalnum;
    TextView ws_home_server_sync_filepath;
    ProgressBar ws_home_server_sync_progressbar;
    TextView ws_home_server_sync_log;
    //加载发来的数据
    StringBuffer mShowBuffer = new StringBuffer();
    //是否已连接
    boolean isConnected = false;
    //线程池
    ExecutorService fixedThreadPool;
    //进度
    int progress = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ws_home_server);
        StatusBarUtils.setDarkStatusWhite(this,R.color.white);

        //EventBus注册
        EventBus.getDefault().register(this);

        ws_home_server_back = findViewById(R.id.ws_home_server_back);
        ws_home_server_group_list = findViewById(R.id.ws_home_server_group_list);
        ws_home_server_window = findViewById(R.id.ws_home_server_window);
        ws_home_server_location_ip = findViewById(R.id.ws_home_server_location_ip);
        ws_home_server_location_port = findViewById(R.id.ws_home_server_location_port);
        ws_home_server_serverstatus = findViewById(R.id.ws_home_server_serverstatus);
        ws_home_server_clientstatus = findViewById(R.id.ws_home_server_clientstatus);

        ws_home_server_sync_linearlayout = findViewById(R.id.ws_home_server_sync_linearlayout);
        ws_home_server_sync_sendnum = findViewById(R.id.ws_home_server_sync_sendnum);
        ws_home_server_sync_totalnum = findViewById(R.id.ws_home_server_sync_totalnum);
        ws_home_server_sync_filepath = findViewById(R.id.ws_home_server_sync_filepath);
        ws_home_server_sync_progressbar = findViewById(R.id.ws_home_server_sync_progressbar);
        ws_home_server_sync_log = findViewById(R.id.ws_home_server_sync_log);

        ws_home_server_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        ws_home_server_group_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getApplicationContext(), ProductGroupListActivity.class));
            }
        });
        ws_home_server_window.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ProductGroupListDatabase groupDb = new ProductGroupListDatabase(getApplicationContext());
                List<ProductGroupModel> groupList = groupDb.selectAllStatusYes();
                if(groupList.size() == 0){
                    ToastBottomUtils.Setinfo(getApplicationContext(),"未添加产品组！");
                    return;
                }
                if(!Settings.canDrawOverlays(getApplicationContext())){
                    startActivity(new Intent(getApplicationContext(), PermissionActivity.class));
                    ToastBottomUtils.Setinfo(getApplicationContext(),"请到设置中授权【悬浮窗】权限！");
                    return;
                }

                if(GetUtil.isServiceWork(getApplicationContext(),getPackageName()+".service.WsWindowService")){
                    stopService(new Intent(getApplicationContext(), WsWindowService.class));
                    ToastBottomUtils.Setinfo(getApplicationContext(),"已关闭服务");
                }else{
                    //打开悬浮窗服务
                    startService(new Intent(getApplicationContext(), WsWindowService.class));
                    ToastBottomUtils.Setinfo(getApplicationContext(),"已开启服务");
                }
            }
        });

        String ip = GetUtil.getIPAddress(getApplicationContext());
        ws_home_server_location_ip.setText(ip);
        ws_home_server_location_port.setText("36688");

        //建立10个固定线程池
        fixedThreadPool = Executors.newFixedThreadPool(10);
        fixedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                //生成对象不要在子线程里，在主线程提前准备好。
                WsServer.ready(getApplicationContext(),ip,36688);
            }
        });
    }

    //=======================接收消息=================================
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MessageEventBus(WsMessageEvent wsMessageEvent){
        switch (wsMessageEvent.getNumber()) {
            case WsStatus.onStart://onStart 服务器就绪
                ws_home_server_serverstatus.setText("已就绪");
                ws_home_server_serverstatus.setTextColor(getColor(R.color.blue));
                break;
            case WsStatus.onOpen://onOpen
                isConnected = WsServer.collections.size()>0;
                ws_home_server_clientstatus.setText(isConnected?"已连接":"已断开");
                ws_home_server_clientstatus.setTextColor(getColor(isConnected?R.color.blue:R.color.black));
                break;
            case WsStatus.onMessageString://onMessage
                MessageReceive(wsMessageEvent.getMessage());
                break;
            case WsStatus.onMessageProgress://传输进度
                //减少更新频率
                if(wsMessageEvent.getProgress() != progress){
                    progress = wsMessageEvent.getProgress();
                    //Log.d(GetUtil.TAG,"[进度]"+progress);
                    ws_home_server_sync_progressbar.setProgress(progress);
                }
                break;
            case WsStatus.onClose://onClose
                isConnected = WsServer.collections.size()>0;
                ws_home_server_clientstatus.setText(isConnected?"已连接":"已断开");
                ws_home_server_clientstatus.setTextColor(getColor(isConnected?R.color.blue:R.color.black));
                break;
            case WsStatus.onError://onError
                mShowBuffer.append(wsMessageEvent.getMessage()+"\n");
                ws_home_server_sync_log.setText(mShowBuffer);
                break;
        }
    }
    //=======================消息处理机制=================================
    public void MessageReceive(String message){
        try {
            JSONObject json = new JSONObject(message);
            String command = json.getString("command");
            switch (command){
                case WsStatus.mateialCheck://客户端请求素材校验
                    JSONObject dataJson = ServerDataTool.getAllData(getApplicationContext());
                    //向客户端发送数据
                    SendMessage(WsStatus.mateialCheck,dataJson.toString());
                    break;
                case WsStatus.mateialSync://客户端请求开始同步
                    //获取要同步文件的个数
                    int snycNum = json.getInt("param");
                    if(snycNum > 0){
                        ws_home_server_window.setEnabled(false);
                        ws_home_server_window.setClickable(false);
                        ws_home_server_sync_linearlayout.setVisibility(View.VISIBLE);
                        //向客户端发送文件完毕状态（开始同步）
                        ws_home_server_sync_totalnum.setText("共"+json.getInt("param")+"个");
                        SendMessage(WsStatus.transFileOver,"");
                    }else{
                        ws_home_server_window.setEnabled(true);
                        ws_home_server_window.setClickable(true);
                        ws_home_server_sync_linearlayout.setVisibility(View.GONE);
                        ToastUtils.Setinfo(getApplicationContext(),"同步完毕",1);
                    }
                    break;
                case WsStatus.transFile://请求发送文件
                    String file_path = json.getString("param");
                    ws_home_server_sync_filepath.setText(file_path);
                    String sendNum = ws_home_server_sync_sendnum.getText().toString();
                    ws_home_server_sync_sendnum.setText(String.valueOf(Integer.valueOf(sendNum)+1));
                    //开始发送文件
                    WsServer.sendFile(file_path);
                    break;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //消息发送模版
    public void SendMessage(String magType, Object obj){
        try {
            JSONObject json = new JSONObject();
            json.put("command",magType);
            json.put("param",obj);
            WsServer.SendMsg(json.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消注册
        EventBus.getDefault().unregister(this);
        //关闭WS
        WsServer.Stop();
        //关闭线程
        fixedThreadPool.shutdownNow();
    }
}